//src/auth/jwt.strategy.ts
import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { jwtSecret } from './constants';
import { UserService } from '../user/user.service';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor(private userService: UserService, private redisService: RedisService) {
    super({
      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      secretOrKey: jwtSecret,
    });
  }

  async validate(payload: { userId: string }) {
    const token = ExtractJwt.fromAuthHeaderAsBearerToken()(payload);
    const cacheToken = await this.redisService.getValue(payload.userId)
    if (!cacheToken) {
      throw new UnauthorizedException('token已过期')
    }
    if (token !== cacheToken) {
      throw new UnauthorizedException('token不正确');
    }
    const user = await this.userService.findOne(payload.userId);
    if (!user) {
      throw new UnauthorizedException('token不正确');
    }

    return user;
  }
}
